package com.hiv.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@Slf4j
public class ZipUtil {

    /**
     * 解压zip文件
     *
     * @param zipPath 文件地址
     * @return 返回解压地址中的 /index.html
     */
    public static String unZip(String zipPath) {
        log.info("解压zip文件 zipPath={}", zipPath);
        String descDir = zipPath.substring(0, zipPath.lastIndexOf("/"));
        String fileName = zipPath.substring(zipPath.lastIndexOf("/"));
        String name = fileName.substring(0, fileName.lastIndexOf("."));

        // 解压路径
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zip = null;
        try {
            // 指定编码，否则压缩包里面不能有中文目录
            zip = new ZipFile(new File(zipPath), Charset.forName("gbk"));
            for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                String outPath = (descDir + File.separator + zipEntryName).replace("/", File.separator);
                // 判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }

                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[2048];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                in.close();
                out.close();
            }
            // 必须关闭，否则无法删除该zip文件
            zip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getFileName(descDir + name);
    }


    /**
     * 获取指定路径下的文件名
     *
     * @param path
     * @return
     */
    private static String getFileName(String path) {
        File f = new File(path);
        if (!f.exists()) {
            System.out.println(path + " not exists");
            return null;
        }

        File fa[] = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            File fs = fa[i];
            if (!fs.isDirectory() && fs.getName().equals("index.html")) {
                System.out.println(fs.getName() + " [目录]");
                return fs.getName();
            }
        }

        return null;
    }
}